package com.app.controller;

import com.app.common.Result;
import com.app.enums.StatusCodeEnum;
import com.app.model.AdminUserModel;
import com.app.model.AreaModel;
import com.app.model.TimeWarningModel;
import com.app.model.UserModel;
import com.app.server.AdminUserService;
import com.app.server.UserService;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.vo.UserLoginVo;
import com.app.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;


@RestController
@Controller
@RequestMapping("/sbbz/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AdminUserService adminUserService;


    //用户列表
    @GetMapping("/userList")
    public Result<Object> userList(Integer page, Integer limit, String keyword) {
        UserVo list = userService.getList(page, limit, keyword);
        return Result.success(list);
    }

    //删除用户
    @GetMapping("/deleteUser")
    public Result<Object> deleteUser(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        userService.deleteById(id);
        return Result.success("删除成功");
    }

    //详情
    @GetMapping("/getUserById")
    public Result<Object> getUserInfo(Integer id) {
        UserModel userModel = userService.selectById(id);
        userModel.setOpenId(null);
        return Result.success(userModel);
    }

    //修改状态
    @GetMapping("/updateStatus")
    public Result<Object> updateStatus(Integer id, Integer status, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        userService.updateStatus(id, status);
        return Result.success("修改成功");
    }

    //获取openid
    @GetMapping("/getOpenid")
    public Result<UserLoginVo> getOpenid(String code, HttpServletRequest request) throws LoginException {
        //微信登录
        UserModel user = userService.getOpenid(code, request);
        //生成token
        String token = TokenUtils.sign(user.getOpenId());
        UserLoginVo userLoginVO = UserLoginVo.builder()
                .user(user)
                .token(token)
                .build();
        System.out.println(token);
        return Result.success(userLoginVO);
    }


    //获取手机号
    @GetMapping("/getPhone")
    public Result<Object> getPhone(String code, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(StatusCodeEnum.STATUS405.getCode(), StatusCodeEnum.STATUS405.getMsg());
        }
        String mobile = TokenUtils.nothingness(token);
        UserModel user = userService.getUserByOpenid(mobile);
        if (user == null) {
            return Result.error(StatusCodeEnum.STATUS406.getCode(), StatusCodeEnum.STATUS406.getMsg());
        }
        return Result.success(userService.getPhone(code, request, user));
    }


    //新增和修改
    @PostMapping("/addAndUpdateUser")
    public Result<Object> addAndUpdateUser(@RequestBody UserModel userModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(StatusCodeEnum.STATUS405.getCode(), StatusCodeEnum.STATUS405.getMsg());
        }
        String mobile = TokenUtils.nothingness(token);
        UserModel userInfo = userService.getUserByOpenid(mobile);
        if (userInfo == null) {
            return Result.error(StatusCodeEnum.STATUS406.getCode(), StatusCodeEnum.STATUS406.getMsg());
        }
        UserModel user = userService.getById(userInfo.getId());
        if (userModel.getArea() != null && !userModel.getArea().isEmpty()) {
            StringBuilder s2 = new StringBuilder();
            StringBuilder s3 = new StringBuilder();
            for (AreaModel areaModel : userModel.getArea()) {
                s2.append(areaModel.getValue()).append(",");
                s3.append(areaModel.getText()).append("/");
            }
            userModel.setAreaId(s2.substring(0, s2.toString().length() - 1));
            userModel.setAreaName(s3.substring(0, s3.toString().length() - 1));
        }
        if (user != null) {
            userModel.setUpdateTime(CommonHelp.getNowTimestamp());
            userService.updateById(userModel);
            return Result.success("修改成功");
        } else {
            userModel.setOpenId(userInfo.getOpenId());
            userModel.setCreateTime(CommonHelp.getNowTimestamp());
            userService.save(userModel);
            return Result.success("添加成功");
        }
    }

    //管理端修改用户状态
    @GetMapping("/updateUserStatus")
    public Result<Object> updateUserStatus(@RequestParam("id") Integer id,
                                           @RequestParam("status") Integer status, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        UserModel userModel = new UserModel();
        userModel.setId(id);
        userModel.setStatus(status);
        userService.updateById(userModel);
        return Result.success("修改成功");
    }

    //小程序端登录后的查询个人信息
    @GetMapping("/getUserInfo")
    public Result<Object> getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(StatusCodeEnum.STATUS405.getCode(), StatusCodeEnum.STATUS405.getMsg());
        }
        String mobile = TokenUtils.nothingness(token);
        UserModel user = userService.getUserByOpenid(mobile);
        if (user == null) {
            return Result.error(StatusCodeEnum.STATUS406.getCode(), StatusCodeEnum.STATUS406.getMsg());
        }
        UserModel userModel = userService.selectUserById(user.getId());
        return Result.success(userModel);
    }


    //获取小程序二维码
//    @PostMapping("/getCode")
//    public Result<Object> getCode(HttpServletRequest request) throws Exception {
//            return  Result.success(WxQrCode.generateQrCode( "C:/upload/"+ "小程序码"+".png","pages/index/index",WxQrCode.postToken(WXConstant.APPID,WXConstant.SECRET)));
//    }

}
